package www17nyy.com.itext5;

import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class HtmlToPdf {

    public static String getHtml() {
        try {
            InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("templates/test.html");
            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes);
            String str = new String(bytes);
            return str;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }


    public static void toPdf(String html) {
        FileOutputStream fos = null;
        try {

            fos = new FileOutputStream(new File("test.pdf"));
            ITextRendererExt renderer = new ITextRendererExt(new ITextRenderer());
            renderer.setDocumentFromString(html);
            PdfXofyBuilder pdfXofyBuilder = new PdfXofyBuilder();
            renderer.setPdfPageEvent(pdfXofyBuilder);

            renderer.layout();
            renderer.createPDF(fos);
            renderer.finishPDF();
            renderer = null;
        } catch (Exception e) {
            throw new RuntimeException("generate pdf failed");
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {

                }
            }
        }
    }


}